package com.yix.admin.modules.system.controller;

import com.yix.admin.modules.system.entity.SysDict;
import com.yix.admin.modules.system.entity.query.SysDictQuery;
import com.yix.admin.modules.system.service.SysDictService;
import com.yix.common.exception.BadRequestException;
import com.yix.logging.annotation.LogAop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * @author wdx
 * @version 1.0
 * @Description TODO
 * @date 2021/2/5 13:54
 */
@RestController
@Api(tags = "系统：字典管理")
@RequestMapping("/api/dict")
public class SysDictController {

    @Autowired
    private SysDictService sysDictService;

    private static final String ENTITY_NAME = "dict";

    @ApiOperation("查询字典")
    @GetMapping(value = "/all")
    @PreAuthorize("@el.check('dict:list')")
    public ResponseEntity<Object> queryAll(){
        return new ResponseEntity<>(sysDictService.queryAll(new SysDictQuery()),HttpStatus.OK);
    }

    @ApiOperation("查询字典")
    @GetMapping
    @PreAuthorize("@el.check('dict:list')")
    public ResponseEntity<Object> query(SysDictQuery resources, Pageable pageable){
        return new ResponseEntity<>(sysDictService.queryAll(resources,pageable), HttpStatus.OK);
    }

    @LogAop("新增字典")
    @ApiOperation("新增字典")
    @PostMapping
    @PreAuthorize("@el.check('dict:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody SysDict resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        sysDictService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @LogAop("修改字典")
    @ApiOperation("修改字典")
    @PutMapping
    @PreAuthorize("@el.check('dict:edit')")
    public ResponseEntity<Object> update(@Validated(SysDict.Update.class) @RequestBody SysDict resources){
        sysDictService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @LogAop("删除字典")
    @ApiOperation("删除字典")
    @DeleteMapping
    @PreAuthorize("@el.check('dict:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){
        sysDictService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
